package com.moon.controller;

import com.moon.entity.Admin;
import com.moon.service.AdminService;
import com.moon.utils.BaseController;
import com.moon.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/admin")
public class AdminController extends BaseController {
    @Autowired
    private AdminService adminService;

    @RequestMapping("/login")
    public String login(String account, String password, HttpSession session, HttpServletResponse response, HttpServletRequest request) {
        Admin admin = adminService.selectByAccountAndPassword(account, password);
        if (admin == null) {
            return "redirect:/login";
        }
        //success
//        session.setAttribute("admin",admin);
        admin.setPassword("s"); //脱敏
        String token = JwtUtils.getToken(admin, 60000);  //得到token
        super.setCookieVal(response,"token",token);

//        Admin admin1 = new Admin();
//        admin1.setId(admin.getId());
//        admin1.setLoginstr(request.getSession().getId());
//        adminService.update(admin1);
//        session.setAttribute("admin", admin);
        return "redirect:/";
    }

    //登入接口2:专供纯前端项目/手机端项目访问
    @RequestMapping("/loginx")
    @ResponseBody
    public String loginx(String account, String password) {
        System.out.println("后端收到");
        Admin admin = adminService.selectByAccountAndPassword(account, password);
        if (admin == null) {
            return "fail";
        }
        //success
        admin.setPassword("s");//脱敏
        String token = JwtUtils.getToken(admin, 3600000);
        return token;
    }
    @RequestMapping("/selectAll")
    @ResponseBody
    public List<Admin> selectAll(){
        return adminService.selectAll();
    }

}
